package com.example.myforum.controller;

import com.example.myforum.common.AppResult;
import com.example.myforum.common.ResultCode;
import com.example.myforum.config.AppConfig;
import com.example.myforum.exception.ApplicationException;
import com.example.myforum.model.UpdateUser;
import com.example.myforum.model.User;
import com.example.myforum.service.IUserService;
import com.example.myforum.utils.MD5Utils;
import com.example.myforum.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "用户模块")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult login(
            @ApiParam(value = "⽤户名") @RequestParam("username") @NonNull String username,
            @ApiParam(value = "密码") @RequestParam("password") @NonNull String password,
            @ApiParam(value = "重复密码") @RequestParam("repeatPassword") @NonNull String repeatPassword,
            @ApiParam(value = "昵称") @RequestParam("nickname") @NonNull String nickname,
            @ApiParam(value = "用户权限") @RequestParam("permission") @NonNull int permission) {

        log.info("permission" + permission);
        if (!password.equals(repeatPassword)) {
            log.info("两次密码不一致");
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        log.info("用户输入的password:{}", password);
        String salt = UUIDUtils.getUUID_32();
        String md5Password = MD5Utils.md5Salt(password, salt);
        log.info("加密之后的password:{}", md5Password);
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        user.setPassword(md5Password);
        user.setSalt(salt);
        user.setPermission(permission);

        iUserService.createNormalUser(user);

        return AppResult.success();
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult register(
            HttpServletRequest req,
            @ApiParam(value = "⽤户名") @RequestParam("username") @NonNull String username,
            @ApiParam(value = "密码") @RequestParam("password") @NonNull String password) {
        log.info(username + "进行登录");
        User userLogin = iUserService.login(username, password);
        if (userLogin == null) {
            return AppResult.fail(ResultCode.FAILED_LOGIN);
        }
        HttpSession session = req.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, userLogin);
        return AppResult.success();
    }

    @ApiOperation("用户退出")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        log.info("用户正在退出");
        // 获取session对象
        HttpSession session = request.getSession(false);
        if (session != null) {
            // 注销session
            session.invalidate();
        }
        // 退出成功响应
        return AppResult.success();
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/getInfo")
    public AppResult getInfo(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session == null) {
            log.info("getInfo: session为空");
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        User attribute = (User) session.getAttribute(AppConfig.USER_SESSION);
        return AppResult.success(attribute);
    }

    @ApiOperation("用户修改")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(
            @ApiParam("修改用户信息") @RequestBody User updateUser,
            HttpServletRequest req) {
        updateUser.setUpdateTime(new Date());
        System.out.println(updateUser);
        int modifyInfoRet = iUserService.modifyInfo(updateUser);
        if (modifyInfoRet != 1) {
            log.warn("modifyInfo:" + "更新失败");
            throw new ApplicationException(AppResult.fail("更新失败"));
        }
        HttpSession session = req.getSession(false);
        if (session == null) {
            log.warn("modifyInfo:" + "session为空,存入session失败");
            throw new ApplicationException(AppResult.fail("更新失败"));
        }
        User updateNewUser = iUserService.getUserInfo(updateUser.getId());
        session.setAttribute(AppConfig.USER_SESSION, updateNewUser);
        return AppResult.success("更新信息成功");
    }

    @ApiOperation("用户修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPwd(@ApiParam("修改参数") @RequestBody UpdateUser updateUser) {
        //1.校验一下输入参数是否为空
        if (updateUser == null || !StringUtils.hasText(updateUser.getNewPassword())
                || !StringUtils.hasText(updateUser.getOldPassword()) || !StringUtils.hasText(updateUser.getPasswordRepeat())
                || updateUser.getId() == null || updateUser.getId() <= 0) {
            log.warn("modifyPwd:" + "updateUser输入参数为空|id不合法");
            return AppResult.fail("updateUser输入参数为空|id不合法");
        }
        //2.新密码和重复密码是否一致
        if (!updateUser.getNewPassword().equals(updateUser.getPasswordRepeat())) {
            log.warn("modifyPwd:" + "updateUser两次输入密码不一致");
            return AppResult.fail("两次输入密码不一致");
        }
        iUserService.modifyPwd(updateUser);
        return AppResult.success("修改密码成功");
    }

}
